package com.easemob.helpdesk.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;

import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.helpdesk.AppConfig;
import com.easemob.helpdesk.activity.history.HistoryChatActivity;
import com.easemob.helpdesk.activity.transfer.TransferActivity;
import com.easemob.helpdesk.adapter.ChatAdapter;
import com.easemob.helpdesk.bean.User;
import com.easemob.helpdesk.recorder.MediaManager;
import com.easemob.helpdesk.utils.DialogUtils;
import com.easemob.helpdesk.widget.popupwindow.HistorySessionMore;
import com.housekeeperapp.R;
import com.hyphenate.kefusdk.HDDataCallBack;
import com.hyphenate.kefusdk.entity.HDCategorySummary;
import com.hyphenate.kefusdk.entity.HDMessage;
import com.hyphenate.kefusdk.entity.HDSession;
import com.hyphenate.kefusdk.entity.user.HDVisitorUser;
import com.hyphenate.kefusdk.manager.session.SessionManager;
import com.net.ApiService;
import com.net.BaseResponse;
import com.net.HKHttpUtils;
import com.net.HKResponseResultCallBack;
import com.zdxd.tagview.Tag;

import java.util.List;


import retrofit2.Call;

import static com.easemob.helpdesk.fragment.WaitAccessFragment.REQUEST_CODE_ALERT_DIALOG_TRANSFER;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

/**
 * Created by xiaolong.wei on 2019/6/18.
 */

public class PreviewWaitingSessionDialog extends BaseActivityV2 implements  View.OnClickListener {

    private final String TAG = getClass().getSimpleName();


    @Override
    protected void initFindView() {

        mRecyclerView=findViewById(R.id.history_listview);
        userName=findViewById(R.id.user_name);
        swipeRefreshLayout=findViewById(R.id.chat_swipe_layout);

        findViewById(R.id.btn_call_back).setOnClickListener(this);
        findViewById(R.id.transfer_session).setOnClickListener(this);
        findViewById(R.id.close_dialog).setOnClickListener(this);


    }

    protected RecyclerView mRecyclerView;


    protected TextView userName;



    /**
     * 加载更多的View
     */
    public SwipeRefreshLayout swipeRefreshLayout;

    /**
     * 是否有更多的数据
     */
    private boolean haveMoreData = true;
    /**
     * 当前是否正在加载数据
     */
    private boolean isLoadding = false;
    public ChatAdapter mAdapter;

    private Dialog pd = null;
    private HDVisitorUser visitorUser;
    private String sessionId = null;

    private SessionManager sessionManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppConfig.setFitWindowMode(this);
        setContentView(R.layout.preview_waiting_session_activity);
        initFindView();
        Intent intent = getIntent();
        sessionId = intent.getStringExtra("visitorid");
        visitorUser = intent.getParcelableExtra("user");
//        originType = intent.getStringExtra("originType");
//        techChannelName = intent.getStringExtra("techChannelName");
        long chatGroupId = intent.getLongExtra("chatGroupId", 0);
        sessionManager = new SessionManager(chatGroupId, sessionId, visitorUser, null);
        initDatas();
        LoadRemoteMsg();
    }



//    private void getUserInfo(final HDVisitorUser visitorUser) {
//        final String val = visitorUser.getUsername();
//
//        if(!TextUtils.isEmpty(val) && val.contains("#")){
//            showLoading(getResources().getString(R.string.loading_getdata));
//            String uid = val.split("#")[0];
//
//            ApiService apiService = HKHttpUtils.getApiService();
//            Call<BaseResponse<User>> call = apiService.getUserById(MainActivity.ticket,String.valueOf(uid));
//            call.enqueue(new HKResponseResultCallBack<User>() {
//                @Override
//                public void onSuccess(User user) {
//                    if (user != null){
//                        if(!TextUtils.isEmpty(user.getName())){
//                            userName.setText(user.getName());
//                        }else{
//                            userName.setText(visitorUser.getNicename());
//                        }
//
////                        truename = user.getName();
////                        user_phone = user.getPhone();
////                        username = val;
////                        addr = user.getHomeAddress();
//                    }
//                    if(isShowLoading()){
//                        closeDialog();
//                    }
//                }
//
//                @Override
//                public void onGetDataFailed(int cd, String msg) {
//                    if(isShowLoading()){
//                        closeDialog();
//                    }
//                    Toast.makeText(PreviewWaitingSessionDialog.this, "请求失败:"+msg, Toast.LENGTH_SHORT).show();
//                }
//
//                @Override
//                public void onFailed(Call call, Throwable t) {
//                    if(isShowLoading()){
//                        closeDialog();
//                    }
//                    Toast.makeText(PreviewWaitingSessionDialog.this, "请求失败", Toast.LENGTH_SHORT).show();
//                }
//            });
//
//        }
//
//    }


    private void initDatas() {
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);

        userName.setText(visitorUser.getUsername());
//        getUserInfo(visitorUser);

        mAdapter = new ChatAdapter(this, sessionManager, mRecyclerView, visitorUser.getUsername());
        mRecyclerView.setAdapter(mAdapter);


        swipeRefreshLayout.setColorSchemeResources(R.color.holo_blue_bright, R.color.holo_green_dark,
                R.color.holo_orange_light, R.color.holo_red_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        int firstVisibilePosition = layoutManager.findFirstVisibleItemPosition();
                        if (firstVisibilePosition == 0 && !isLoadding && haveMoreData) {
                            sessionManager.asyncGetSessionMessages(new HDDataCallBack<List<HDMessage>>() {
                                @Override
                                public void onSuccess(final List<HDMessage> value) {
                                    swipeRefreshLayout.setRefreshing(false);
                                    isLoadding = false;
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (value.isEmpty()){
                                                haveMoreData = false;
                                                Toast.makeText(mActivity, getString(R.string.txt_no_more_message), Toast.LENGTH_SHORT).show();
                                                return;
                                            }else{
                                                mAdapter.refresh();
                                            }
                                        }
                                    });
                                }

                                @Override
                                public void onError(int error, String errorMsg) {
                                    if (isFinishing()) {
                                        return;
                                    }
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            isLoadding = false;
                                            swipeRefreshLayout.setRefreshing(false);
                                        }
                                    });

                                }
                            });
                        } else {
                            Toast.makeText(mActivity, getString(R.string.txt_no_more_message), Toast.LENGTH_SHORT).show();
                        }
                        if (swipeRefreshLayout != null){
                            swipeRefreshLayout.setRefreshing(false);
                        }


                    }
                }, 1000);
            }
        });


    }


    private void LoadRemoteMsg() {
        sessionManager.asyncGetSessionMessages(new HDDataCallBack<List<HDMessage>>() {
            @Override
            public void onSuccess(List<HDMessage> value) {
                if (isFinishing()) {
                    return;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isShowLoading()) {
                            closeDialog();
                        }
                        mAdapter.refresh();
                    }
                });
            }

            @Override
            public void onError(int error, String errorMsg) {
                if (isFinishing()) {
                    return;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isShowLoading()) {
                            closeDialog();
                        }
                        Toast.makeText(mActivity, "网络请求失败！", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }




    private void closeDialog(){
        if (pd != null) {
            pd.dismiss();
            pd = null;
        }
    }

    private void showLoading(String msg){
        pd = DialogUtils.getLoadingDialog(this, msg);
        pd.show();
    }

    private boolean isShowLoading(){
        if (pd != null && pd.isShowing()){
            return true;
        }
        return false;
    }

/*    @OnClick({R.id.btn_call_back,R.id.transfer_session,R.id.close_dialog})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.btn_call_back:
                setResult(RESULT_OK,new Intent());
                finish();
                break;
            case R.id.transfer_session:
                startActivityForResult(new Intent(this, TransferActivity.class), REQUEST_CODE_ALERT_DIALOG_TRANSFER);
                break;
            case R.id.close_dialog:
                finish();
                break;
            default:
                break;

        }

    }*/

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            if (requestCode == REQUEST_CODE_ALERT_DIALOG_TRANSFER){
                data.putExtra("isTransfer",true);
                setResult(RESULT_OK,data);
                finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeDialog();
    }

    @Override
    public void onClick(View view) {

        if(view.getId()==R.id.btn_call_back){
            setResult(RESULT_OK,new Intent());
            finish();
        }
        else if(view.getId()==R.id.transfer_session){
            startActivityForResult(new Intent(this, TransferActivity.class), REQUEST_CODE_ALERT_DIALOG_TRANSFER);
        }else if(view.getId()==R.id.close_dialog){
            startActivityForResult(new Intent(this, TransferActivity.class), REQUEST_CODE_ALERT_DIALOG_TRANSFER);
        }

    }
}
